package com.njcb.ams.support.trade.filter;

import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.njcb.ams.pojo.dto.standard.PageQuery;
import com.njcb.ams.pojo.dto.standard.PageResponse;
import com.njcb.ams.factory.domain.AppContext;
import com.njcb.ams.store.page.Page;
import com.njcb.ams.store.page.PageHandle;
import com.njcb.ams.support.annotation.TradeFilter;
import com.njcb.ams.util.AmsUtils;

/**
 * 根据交易定义的请求参数、如果请求参数继承了PageQuery对象、则默认实现分页
 */
@Service
@Lazy(false)
@TradeFilter(priority = 0)
public class PageQueryFilter implements TradeLayerFilter {
	private static final Logger logger = LoggerFactory.getLogger(PageQueryFilter.class);
	
	public static PageQueryFilter getInstance() {
		return AppContext.getBean(PageQueryFilter.class);
	}
	
	@Override
	public Object doFilter(TradeFilterChain filterChain) throws Throwable {
		ProceedingJoinPoint pjd = filterChain.getJoinPoint();
		//分页查询请求对象
		Boolean isPageQuery = false;
		//分页查询请求对象
		isPageQuery = startPage(pjd.getArgs());
		Object result = filterChain.doFilter(filterChain);
		// 分页查询返回对象
		if (isPageQuery && null != result) {
			endPage(result,pjd);
		}
		return result;
	}
	
	
	/**
	 * 自动分页时开始分页
	 * 方法功能描述：
	 * @param args
	 * @return
	 */
	private boolean startPage(Object[] args) {
		boolean isPageQuery = false;
		if(null != args && args.length == 1 && null != args[0]){
			if (PageQuery.class.isAssignableFrom(args[0].getClass())) {
				PageQuery pageQuery = (PageQuery) args[0];
				if(AmsUtils.isNotNull(pageQuery.getPage()) && AmsUtils.isNotNull(pageQuery.getRows())){
					isPageQuery = true;
					Page inPage = new Page(pageQuery.getPage(),pageQuery.getRows());
					PageHandle.startPage(inPage);
				}else{
					logger.info("交易分页参数为空");
				}
			}
		}
		return isPageQuery;
	}
	
	/**
	 * 自动分页时结束分页
	 * 方法功能描述：
	 * @param result
	 */
	private void endPage(Object result,ProceedingJoinPoint pjd) {
		Page page = PageHandle.endPage();
		if(page.getTotal() == 0 || null == page.getResult()){
			return;
		}
		PageQuery pageQuery = (PageQuery) pjd.getArgs()[0];
		pageQuery.setTotal(page.getTotal());
		if (PageResponse.class.isAssignableFrom(result.getClass())) {
			PageResponse<?> response = (PageResponse<?>)result;
			response.setResult(page.getResult());
			response.setTotal(page.getTotal());
		}
	}

}
